package com.facebook.react.modules.upgrade;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.IBinder;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.ContextCompat;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
//import com.facebook.react.modules.core.DeviceEventManagerModule;
//import com.sinochem.ubmp.app.MainActivity;

/**
 * Created by Song on 2017/7/10.
 */
public class UpgradeModule extends ReactContextBaseJavaModule {

    private static ReactApplicationContext mContext;
    private static final String EVENT_NAME = "LOAD_PROGRESS";

    private DownloadService.DownloadBinder downloadBinder;

    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder=(DownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    public UpgradeModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.mContext = reactContext;

        Intent intent = new Intent(mContext,DownloadService.class);
        //这一点至关重要，因为启动服务可以保证DownloadService一直在后台运行，绑定服务则可以让mContext和DownloadService
        //进行通信，因此两个方法的调用都必不可少。
        mContext.startService(intent);  //启动服务
        mContext.bindService(intent,connection, mContext.BIND_AUTO_CREATE);//绑定服务
        /**
         *运行时权限处理：我们需要再用到权限的地方，每次都要检查是否APP已经拥有权限
         * 下载功能，需要些SD卡的权限，我们在写入之前检查是否有WRITE_EXTERNAL_STORAGE权限,没有则申请权限
         */
//       if(ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//               != PackageManager.PERMISSION_GRANTED){
//           ActivityCompat.requestPermissions(mContext.getCurrentActivity(),
//                   new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                   1);
//       }
    }

    @Override
    public String getName() {
        return "upgrade";
    }

    @ReactMethod
    public void startUpgrade(String url) {
        System.out.println("UpgradeModule-->" + url );
        if(downloadBinder==null){
            System.out.println("UpgradeModule-->" + url );
            return;
        }
        downloadBinder.startDownload(mContext,url,"apk");
    }

    public static void sendProgress(int msg) {
        //mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(EVENT_NAME, msg);
    }

}
